package storage

import (
	"beesoft.ink/application/media/app/helper/helper"
	"github.com/gogf/gf/v2/os/gfile"
	"os"
	"strings"
)

var File = file{}

type file struct {
	appRootDir string
}

func (r *file) FormatFilePath(path string, trimBackslash ...bool) string {
	path = helper.Trim(path)
	if path == "" {
		return ""
	}

	path = helper.Replace(path, "\\", "/")
	if trimBackslash != nil && len(trimBackslash) > 0 && trimBackslash[0] {
		path = strings.TrimSpace(strings.Trim(path, "/"))
	}
	return path
}

func (r *file) GetAppRootDir() string {
	if r.appRootDir != "" {
		return r.appRootDir
	}

	r.appRootDir = gfile.SelfDir()
	if gfile.Name(r.appRootDir) == "bin" {
		r.appRootDir = gfile.Dir(r.appRootDir)
	}

	r.appRootDir = r.FormatFilePath(r.appRootDir)
	return r.appRootDir
}
func (r *file) GetStorageDir(subDir ...string) string {
	storageDir := r.GetAppRootDir() + "/storage"
	s := r.FormatFilePath(helper.Join(subDir, "/"), true)
	if s != "" {
		storageDir = storageDir + "/" + s
	}
	if !gfile.Exists(storageDir) || !gfile.IsDir(storageDir) {
		err := os.MkdirAll(storageDir, 0755)
		if err != nil {
			return ""
		}
	}

	return storageDir
}
